package com.finupgroup.postloan.generator;

import com.baomidou.mybatisplus.annotations.TableLogic;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.annotations.Version;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.finupgroup.postloan.generator.config.builder.ConfigBuilder;
import com.finupgroup.postloan.generator.config.po.TableField;
import com.finupgroup.postloan.generator.config.po.TableInfo;
import com.finupgroup.postloan.generator.engine.AbstractTemplateEngine;
import com.finupgroup.postloan.generator.engine.FreemarkerTemplateEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.Serializable;
import java.util.List;

/**
 * 生成文件
 *
 * @author YueQingwei
 * @since 2018-04-10
 */
public class AutoGenerator {

    private static final Logger logger = LoggerFactory.getLogger(AutoGenerator.class);
    /**
     * 配置信息
     */
    protected ConfigBuilder config;

    public static void main(String[] args) {
        new AutoGenerator().execute();
    }

    /**
     * 生成代码
     */
    public void execute() {
        logger.info("==========================准备生成文件...==========================");
        // 初始化配置
        config = new ConfigBuilder();
        cleanSourceCode(new File(config.getGlobalConfig().getOutputDir()));
        // 模板引擎初始化执行文件输出
        AbstractTemplateEngine templateEngine = new FreemarkerTemplateEngine();
        templateEngine.init(this.pretreatmentConfigBuilder(config)).mkdirs().batchOutput();
        logger.info("==========================文件生成完成！！！==========================");
    }

    private static void cleanSourceCode(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children == null) {
                return;
            }
            for (String aChildren : children) {
                cleanSourceCode(new File(dir, aChildren));
            }
        }
        dir.delete();
    }

    /**
     * <p>
     * 预处理配置
     * </p>
     *
     * @param config 总配置信息
     * @return 解析数据结果集
     */
    protected ConfigBuilder pretreatmentConfigBuilder(ConfigBuilder config) {
        /**
         * 表信息列表
         */
        List<TableInfo> tableList = config.getTableInfoList();
        for (TableInfo tableInfo : tableList) {
            /* ---------- 添加导入包 ---------- */
            // 表注解
            tableInfo.setImportPackages(TableName.class.getCanonicalName());

            if (tableInfo.isLogicDelete(config.getStrategyConfig().getLogicDeleteFieldName())) {
                // 逻辑删除注解
                tableInfo.setImportPackages(TableLogic.class.getCanonicalName());
            }
            if (StringUtils.isNotEmpty(config.getStrategyConfig().getVersionFieldName())) {
                // 乐观锁注解
                tableInfo.setImportPackages(Version.class.getCanonicalName());
            }
            if (StringUtils.isNotEmpty(config.getSuperEntityClass())) {
                // 父实体
                tableInfo.setImportPackages(config.getSuperEntityClass());
            } else {
                tableInfo.setImportPackages(Serializable.class.getCanonicalName());
            }
            // Boolean类型is前缀处理
            if (config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix()) {
                for (TableField field : tableInfo.getFields()) {
                    if (field.getPropertyType().equalsIgnoreCase("boolean") && field.getPropertyName().startsWith("is")) {
                        field.setPropertyName(StringUtils.removePrefixAfterPrefixToLower(field.getPropertyName(), 2));
                    }
                }
            }
        }
        return config.setTableInfoList(tableList);
    }
}
